package com.fundcrawler.h2;

import lombok.extern.slf4j.Slf4j;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.CharBuffer;
import java.nio.charset.StandardCharsets;

/**
 * @Description:
 * @Version 1.0, 2021/5/18
 * @Author Tim
 */
@Slf4j
public class IOPrintUtil {
    public static void printInputStream(InputStream is) throws IOException {
        InputStreamReader isr = new InputStreamReader(is, StandardCharsets.UTF_8);
        CharBuffer buffer = CharBuffer.allocate(8*1024);
        int size = isr.read(buffer);
        while(size!=-1){
            buffer.flip();
            log.info(buffer.toString());
            buffer.clear();
            size = isr.read(buffer);
        }
    }

    public static String inputStreamToStr(InputStream inputStream){
        if(inputStream==null){
            return null;
        }
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
        try {
            StringBuilder result = new StringBuilder();
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                result.append(line);
            }
            return result.toString();
        } catch (Exception e) {
            try {
                inputStream.close();
                bufferedReader.close();
            } catch (Exception e1) {
            }
        }
        return null;
    }

}
